<template>
  <div class="shop-owner-form">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      size="default"
    >
      <!-- 基本信息 -->
      <el-card class="form-section" shadow="never">
        <template #header>
          <span class="section-title">基本信息</span>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="业主姓名" prop="ownerName">
              <el-input
                v-model="formData.ownerName"
                placeholder="请输入业主姓名"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业主类型" prop="ownerType">
              <el-radio-group v-model="formData.ownerType">
                <el-radio :value="1">个人</el-radio>
                <el-radio :value="2">企业</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="ownerPhone">
              <el-input
                v-model="formData.ownerPhone"
                placeholder="请输入联系电话"
                maxlength="20"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="ownerIdCard">
              <el-input
                v-model="formData.ownerIdCard"
                placeholder="请输入身份证号"
                maxlength="18"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="formData.ownerType === 2">
          <el-col :span="12">
            <el-form-item label="企业名称" prop="companyName">
              <el-input
                v-model="formData.companyName"
                placeholder="请输入企业名称"
                maxlength="100"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业执照号" prop="companyLicense">
              <el-input
                v-model="formData.companyLicense"
                placeholder="请输入营业执照号"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 个人类型业主的营业执照字段 -->
        <el-row :gutter="20" v-if="formData.ownerType === 1">
          <el-col :span="12">
            <el-form-item label="营业执照号" prop="companyLicense">
              <el-input
                v-model="formData.companyLicense"
                placeholder="请输入营业执照号（可选）"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系地址" prop="contactAddress">
              <el-input
                v-model="formData.contactAddress"
                placeholder="请输入联系地址"
                maxlength="200"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="formData.email"
                placeholder="请输入邮箱"
                maxlength="100"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio :value="1">启用</el-radio>
                <el-radio :value="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            placeholder="请输入备注信息"
            :rows="3"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-card>

      <!-- 店铺关联 -->
      <el-card class="form-section" shadow="never">
        <template #header>
          <span class="section-title">店铺关联</span>
        </template>
        
        <ShopSelector
          v-model="formData.shopRelations"
          :disabled="mode === 'edit'"
        />
      </el-card>

    </el-form>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        {{ mode === 'add' ? '新增' : '保存' }}
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { shopOwnerApi } from '@/api/shop-owner'
import { mockShopList, mockShopOwnerList } from '../mockData'
import ShopSelector from './ShopSelector.vue'
import type { ShopOwnerVO, ShopVO, ShopOwnerRelationVO } from '../types'

// Props
interface Props {
  ownerId?: number | null
  mode: 'add' | 'edit'
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  success: []
  cancel: []
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const submitting = ref(false)
const shopList = ref<ShopVO[]>([])

// 表单数据
const formData = reactive({
  ownerName: '',
  ownerPhone: '',
  ownerIdCard: '',
  ownerType: 1,
  companyName: '',
  companyLicense: '',
  contactAddress: '',
  email: '',
  status: 1,
  remark: '',
  shopRelations: [] as ShopOwnerRelationVO[]
})

// 表单验证规则
const formRules: FormRules = {
  ownerName: [
    { required: true, message: '请输入业主姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '业主姓名长度在2到50个字符', trigger: 'blur' }
  ],
  ownerPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  ownerIdCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  ownerType: [
    { required: true, message: '请选择业主类型', trigger: 'change' }
  ],
  companyName: [
    { 
      required: true, 
      message: '请输入企业名称', 
      trigger: 'blur',
      validator: (rule: any, value: any, callback: any) => {
        if (formData.ownerType === 2 && (!value || value.trim() === '')) {
          callback(new Error('请输入企业名称'))
        } else {
          callback()
        }
      }
    }
  ],
  companyLicense: [
    { 
      required: false, 
      message: '请输入营业执照号', 
      trigger: 'blur',
      validator: (rule: any, value: any, callback: any) => {
        // 企业类型业主：营业执照必填
        if (formData.ownerType === 2 && (!value || value.trim() === '')) {
          callback(new Error('请输入营业执照号'))
        } else {
          callback()
        }
      }
    }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 计算属性
const isEdit = computed(() => props.mode === 'edit')

// 生命周期
onMounted(() => {
  loadShopList()
  if (isEdit.value && props.ownerId) {
    loadOwnerInfo()
  }
})

// 方法
const loadShopList = async () => {
  try {
    shopList.value = mockShopList()
  } catch (error) {
    ElMessage.error('加载店铺列表失败')
    console.error('加载店铺列表失败:', error)
  }
}

const loadOwnerInfo = async () => {
  if (!props.ownerId) return
  
  try {
    const mockData = mockShopOwnerList()
    const owner = mockData.find(o => o.id === props.ownerId)
    
    if (owner) {
      Object.assign(formData, {
        ownerName: owner.ownerName,
        ownerPhone: owner.ownerPhone,
        ownerIdCard: owner.ownerIdCard,
        ownerType: owner.ownerType,
        companyName: owner.companyName,
        companyLicense: owner.companyLicense,
        contactAddress: owner.contactAddress,
        email: owner.email,
        status: owner.status,
        remark: owner.remark,
        shopRelations: owner.shopList || []
      })
    }
  } catch (error) {
    ElMessage.error('加载业主信息失败')
    console.error('加载业主信息失败:', error)
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 验证店铺关联
    if (formData.shopRelations.length === 0) {
      ElMessage.warning('请至少选择一个店铺进行关联')
      return
    }
    
    submitting.value = true
    
    // 准备提交数据
    const submitData = {
      ownerName: formData.ownerName,
      ownerPhone: formData.ownerPhone,
      ownerIdCard: formData.ownerIdCard,
      ownerType: formData.ownerType,
      companyName: formData.companyName,
      companyLicense: formData.companyLicense,
      contactAddress: formData.contactAddress,
      email: formData.email,
      status: formData.status,
      remark: formData.remark,
      shopIds: formData.shopRelations.map(relation => relation.shopId)
    }
    
    // 调用API
    const response = await shopOwnerApi.createShopOwner(submitData)
    
    if (response && response.code === 200) {
      ElMessage.success('新增成功')
      emit('success')
    } else {
      ElMessage.error(response?.message || '新增失败')
    }
  } catch (error) {
    if (error !== false) {
      ElMessage.error('提交失败')
      console.error('提交失败:', error)
    }
  } finally {
    submitting.value = false
  }
}

const handleCancel = () => {
  emit('cancel')
}
</script>

<style scoped>
.shop-owner-form {
  padding: 20px;
}

.form-section {
  margin-bottom: 20px;
}

.form-section:last-child {
  margin-bottom: 0;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.form-actions {
  margin-top: 30px;
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.form-actions .el-button {
  margin: 0 8px;
  min-width: 100px;
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #606266;
}

:deep(.el-input__suffix) {
  color: #909399;
  font-size: 14px;
}

:deep(.el-card__header) {
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  padding: 12px 20px;
}

:deep(.el-card__body) {
  padding: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .shop-owner-form {
    padding: 12px;
  }
  
  .form-section {
    margin-bottom: 16px;
  }
  
  .form-actions {
    margin-top: 20px;
    padding-top: 16px;
  }
}
</style>
